package com.yunhe.policyfulfillment.authority.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yunhe.common.exception.ArgumentErrorException;
import com.yunhe.common.exception.ObjectNotFoundException;
import com.yunhe.common.model.mybatis.PageResult;
import com.yunhe.common.util.DateTimeUtils;
import com.yunhe.common.util.MD5Util;
import com.yunhe.policyfulfillment.authority.domain.PolicyCompanyRegistration;
import com.yunhe.policyfulfillment.authority.domain.PolicyCompanyUser;
import com.yunhe.policyfulfillment.authority.domain.PolicyOrg;
import com.yunhe.policyfulfillment.authority.domain.PolicyUser;
import com.yunhe.policyfulfillment.authority.model.ChangePassword;
import com.yunhe.policyfulfillment.authority.model.DisableRecoveryUser;
import com.yunhe.policyfulfillment.authority.model.PolicyCompanyUserQueryCondition;
import com.yunhe.policyfulfillment.authority.model.UserLogin;
import com.yunhe.policyfulfillment.authority.repository.IPolicyOrgRepository;
import com.yunhe.policyfulfillment.authority.repository.PolicyCompanyRegistrationRepository;
import com.yunhe.policyfulfillment.authority.repository.PolicyCompanyUserRepository;
import com.yunhe.policyfulfillment.authority.service.IPolicyOrgService;
import com.yunhe.policyfulfillment.authority.service.PolicyCompanyUserService;
import com.yunhe.policyfulfillment.util.MyHeaderUtil;
import com.yunhe.policyfulfillment.util.SmsUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.yunhe.common.util.CollectionUtil;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * @author zhengbo
 * @date 2021/8/24 17:10
 */
@Service
@Slf4j
public class PolicyCompanyUserServiceImpl implements PolicyCompanyUserService {

    @Autowired
    private PolicyCompanyUserRepository policyCompanyUserRepository;

    @Autowired
    private IPolicyOrgRepository policyOrgRepository;

    @Autowired
    private PolicyCompanyRegistrationRepository policyCompanyRegistrationRepository;

    @Autowired
    private MyHeaderUtil myHeaderUtil;

    private static final String SALT_M = "zcdx";

    private static final String SALT_V = "@zcdx";

    private static final String rootDefaultPassword = "ABcd1234";

    @Autowired
    private IPolicyOrgService policyOrgService;

    @Override
    public PolicyCompanyUser login(UserLogin userLogin) throws ObjectNotFoundException, ArgumentErrorException {
        String password = MD5Util.encode(userLogin.getPassword(), SALT_M);
        log.info("后端再加盐后的password: {}", password);
        PolicyCompanyUser user = policyCompanyUserRepository.searchPolicyCompanyUserByUserAccount(userLogin.getUserAccount());
        if (user == null) {
            throw new ObjectNotFoundException("该账号未注册");
        }
        userLogin.setPassword(password);
        PolicyCompanyUser policyCompanyUser = policyCompanyUserRepository.searchPolicyCompanyUserByUserAccountAndPassword(userLogin.getUserAccount(), password);
        if (policyCompanyUser == null) {
            throw new ArgumentErrorException("账号密码错误");
        }
        String accountIsUseful = "01";
        if (!accountIsUseful.equals(policyCompanyUser.getActivity())) {
            throw new ArgumentErrorException("该账号已被禁用！");
        }
        return policyCompanyUser;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void createPolicyCompanyUser(PolicyCompanyUser policyCompanyUser) throws ArgumentErrorException {
        policyCompanyUser.setCreateTime(new Date());
        policyCompanyUser.setApplyTime(new Date());
        processBeforeSave(policyCompanyUser);
        policyCompanyUserRepository.createPolicyCompanyUserSelective(policyCompanyUser);
    }

    private void processBeforeSave(PolicyCompanyUser policyCompanyUser) throws ArgumentErrorException {
        //校验账号是否重复
        PolicyCompanyUser policyCompanyUserByAccount = policyCompanyUserRepository.searchPolicyCompanyUserByUserAccount(policyCompanyUser.getUserAccount());
        if(policyCompanyUserByAccount != null){
            throw new ArgumentErrorException("当前账号已经存在用户！");
        }
        PolicyCompanyRegistration policyCompanyRegistration = policyCompanyRegistrationRepository.searchPolicyCompanyRegistrationByCompanyUserAccount(policyCompanyUser.getUserAccount());
        if (policyCompanyRegistration != null){
            throw new ArgumentErrorException("当前账号已经存在用户！");
        }
        policyCompanyUser.setPassword(MD5Util.encode(MD5Util.encode(rootDefaultPassword, SALT_V), SALT_M));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deletePolicyCompanyUser(List<Long> ids) {
        if(!CollectionUtil.isEmpty(ids)){
            for (long id : ids) {
                policyCompanyUserRepository.deletePolicyCompanyUserByPrimaryKey(new Long(id).intValue());
            }
        }
    }

    @Override
    public void deletePolicyCompanyUserByPrimaryKey(int id) {
        policyCompanyUserRepository.deletePolicyCompanyUserByPrimaryKey(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updatePolicyCompanyUserByPrimaryKey(PolicyCompanyUser policyCompanyUser) throws ArgumentErrorException {
        PolicyUser headerUser = myHeaderUtil.getHeaderUser();
        if (headerUser == null) {
            throw new ArgumentErrorException("登录信息已失效,请重新登录!");
        }
        policyCompanyUser.setUpdatePerson(headerUser.getId());
        policyCompanyUser.setUpdateTime(new Date());
        policyCompanyUserRepository.updatePolicyCompanyUserByPrimaryKeySelective(policyCompanyUser);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updatePolicyCompanyUserByPrimaryKeySelective(PolicyCompanyUser policyCompanyUser) {
        policyCompanyUserRepository.updatePolicyCompanyUserByPrimaryKeySelective(policyCompanyUser);
    }

    @Override
    public PolicyCompanyUser searchPolicyCompanyUserByPrimaryKey(int id) {
        PolicyCompanyUser policyCompanyUser = policyCompanyUserRepository.searchPolicyCompanyUserByPrimaryKey(id);
        if(policyCompanyUser != null){
            if (policyCompanyUser.getOrgId() != null){
                PolicyOrg policyOrg = policyOrgService.findPolicyOrgByOrgId(policyCompanyUser.getOrgId());
                if(policyOrg != null){
                    policyCompanyUser.setOrgName(policyOrg.getOrgName());
                }

            }
        }
        return policyCompanyUser;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void changePolicyCompanyUserPassword(ChangePassword changePassword) throws ArgumentErrorException {
        PolicyCompanyUser policyCompanyUser1 = searchPolicyCompanyUserByPrimaryKey(Math.toIntExact(changePassword.getId()));
        if(policyCompanyUser1 == null){
            throw new ArgumentErrorException("用户信息不存在！");
        }
        if(!policyCompanyUser1.getPassword().equals(MD5Util.encode(changePassword.getOldPassword(),SALT_M))){
            throw new ArgumentErrorException("旧密码校验错误！");
        }
        PolicyCompanyUser policyCompanyUser = new PolicyCompanyUser();
        policyCompanyUser.setId(changePassword.getId());
        policyCompanyUser.setPassword(MD5Util.encode(changePassword.getNewPassword(),SALT_M));
        policyCompanyUserRepository.updatePolicyCompanyUserByPrimaryKeySelective(policyCompanyUser);
    }

    @Override
    public PolicyCompanyUser searchPolicyCompanyUserByUserAccount(String userAccount) {
        return policyCompanyUserRepository.searchPolicyCompanyUserByUserAccount(userAccount);
    }

    @Override
    public PageResult findPolicyCompanyUserByCondition(PolicyCompanyUserQueryCondition policyCompanyUserQueryCondition) {
        PageResult result = null;
        PageHelper.startPage(policyCompanyUserQueryCondition.getPage(), policyCompanyUserQueryCondition.getSize());
        List<PolicyCompanyUser> policyCompanyUsers = policyCompanyUserRepository.findPolicyCompanyUserByCondition(policyCompanyUserQueryCondition);
        if (!CollectionUtil.isEmpty(policyCompanyUsers)){
            for (PolicyCompanyUser policyCompanyUser : policyCompanyUsers) {
                policyCompanyUser.setPassword(null);
                if (policyCompanyUser.getOrgId() != null){
                    PolicyOrg policyOrg = policyOrgRepository.searchPolicyOrgByPrimaryKey(policyCompanyUser.getOrgId());
                    policyCompanyUser.setOrgName(policyOrg.getOrgName());
                }
            }
            PageInfo<PolicyCompanyUser> pageInfo = new PageInfo<>(policyCompanyUsers);
            result = new PageResult(policyCompanyUserQueryCondition.getPage(), policyCompanyUserQueryCondition.getSize(),
                    (int) pageInfo.getTotal(), policyCompanyUsers);
        }
        return result;
    }

    @Override
    public String resetPassword(List<Long> ids) throws ArgumentErrorException {
        if (CollectionUtil.isEmpty(ids)) {
            throw new ArgumentErrorException("请选择用户进行操作！");
        }
        PolicyUser headerUser = myHeaderUtil.getHeaderUser();
        if (headerUser == null) {
            throw new ArgumentErrorException("登录信息已失效,请重新登录!");
        }
        for (Long id : ids) {
            PolicyCompanyUser policyCompanyUser = policyCompanyUserRepository.searchPolicyCompanyUserByPrimaryKey(new Long(id).intValue());
            policyCompanyUserRepository.updatePassword(Long.valueOf(id), MD5Util.encode(MD5Util.encode(rootDefaultPassword, SALT_V), SALT_M),headerUser.getId());

            //发短信
            /*if (policyCompanyUser != null && policyCompanyUser.getPhone() != null) {
                String phone = policyCompanyUser.getPhone();
                String password = rootDefaultPassword;
                Map<String, String> map = new HashMap<>();
                map.put("code", password);
                String templateCode = "SMS_218727647";
                String templateParam = "{\"code\":\"" + password + "\"}";
                try {
                    SmsUtil.sendSms(phone, map, templateCode, templateParam);
                } catch (Exception e) {
                    throw new ArgumentErrorException("短信发送失败！");
                }
            }*/
        }
        return "已将选择的用户的密码重置为系统默认密码，默认密码为："+rootDefaultPassword;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void disableRecoveryCompanyUser(DisableRecoveryUser disableRecoveryUser) throws ArgumentErrorException {
        PolicyUser headerUser = myHeaderUtil.getHeaderUser();
        if (headerUser == null) {
            throw new ArgumentErrorException("登录信息已失效,请重新登录!");
        }
        if(CollectionUtil.isEmpty(disableRecoveryUser.getIds())){
            throw new ArgumentErrorException("请选择用户进行操作！");
        }
        String remark = null;
        if("01".equals(disableRecoveryUser.getActivity())){
            remark = headerUser.getUserName()+ DateTimeUtils.format(DateTimeUtils.PATTERN.DATETIME.value(),new Date())+"恢复";
        }else {
            remark = headerUser.getUserName()+ DateTimeUtils.format(DateTimeUtils.PATTERN.DATETIME.value(),new Date())+"禁用";
        }
        List<Long> ids = disableRecoveryUser.getIds();
        String finalRemark = remark;
        ids.forEach(id->{
            policyCompanyUserRepository.updateActivity(id,disableRecoveryUser.getActivity(), finalRemark,headerUser.getId());
        });
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void registPolicyCompanyUser(PolicyCompanyUser policyCompanyUser) {
        policyCompanyUserRepository.createPolicyCompanyUserSelective(policyCompanyUser);
    }
}
